package logic

import (
	"context"
	"errors"
	"shop_srv/model/mysql"
	"shop_srv/model/redis"

	"shop_srv/internal/svc"
	"shop_srv/shop"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *shop.CartAddRequest) (*shop.CartAddResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Goods{}
	err := g.FindGoods(in.GoodsId)
	if err != nil {
		logx.Error("未找到该商品")
		return nil, errors.New("未找到该商品")
	}
	if g.ID == 0 {
		logx.Error("未找到该商品")
		return nil, errors.New("未找到该商品")
	}
	stocks := redis.Stock(in.UserId)
	if stocks < in.Num {
		logx.Error("商品库存不足")
		return nil, errors.New("商品库存不足")
	}
	if redis.IsExt(in.UserId, in.GoodsId) {
		err = redis.Add(in.UserId, in.GoodsId, in.Num)
		if err != nil {
			logx.Error("购物车添加失败")
			return nil, errors.New("购物车添加失败")
		}
	} else {
		cart := map[string]interface{}{
			"userId":  in.UserId,
			"goodsId": in.GoodsId,
			"title":   g.Title,
			"price":   g.Price,
			"status":  g.Status,
			"num":     in.Num,
			"check":   1,
		}
		err = redis.CartAdd(cart)
		if err != nil {
			return nil, err
		}
	}

	return &shop.CartAddResponse{Success: true}, nil
}
